<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>async和await的应用</title>
  </head>
  <body>
    <script>
      function sendAjax(url, data) {
        return new Promise((resolve, reject) => {
          // 实例xhr
          const xhr = new XMLHttpRequest()
          // 绑定监听
          let str = ''
          for (let key in data) {
            str += `${key}=${data[key]}&`
          }
          str = str.slice(0, -1)

          xhr.open('GET', url + '?' + str)
          xhr.responseType = 'json'
          xhr.send()

          xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
              if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response)
              } else {
                reject('error!!!')
              }
            }
          }
        })
      }

      ;(async () => {
        try {
          const result1 = await sendAjax('https://api.apiopen.top/api/getShortVideo?', { page: 0, size: 10 })
          console.log('第1次请求成功了', result1)
          const result2 = await sendAjax('https://api.apiopen.top/api/getShortVideo?', { page: 0, size: 10 })
          console.log('第2次请求成功了', result2)
          const result3 = await sendAjax('https://api.apiopen.top/api/getShortVideo?', { page: 0, size: 10 })
          console.log('第3次请求成功了', result3)
        } catch (error) {
          console.log(error)
        }
      })()
    </script>
  </body>
</html>
